/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dnstry;

/**
 *
 * @author Claudiu
 */
public class DnsQuestion {
    String address;
    int length;
    byte [] qName;//bytes with the actual question
    byte [] qType;
    byte [] qClass;
    int [] pointVector;//numbers to be inserted into the address instead of points
    int [] pointPositionVector;//position of the points
    int numberOfPoints;//number of points in the adress ....includes the points before & after the address
    public DnsQuestion (String _address,boolean inverse)
    {
        //address = _address;
        if(inverse)
        {
            address ="."+ _address;
             qName = new byte[address.length()];
        }else{
        address ="."+ _address+ ".";
        qName = new byte[address.length()];
        }
        qType = new byte[2];
        qClass = new byte[2];
        pointPositionVector = new  int[10];
        pointVector = new int[10];
    }
    public void setQName()
    {
        //qName = address.getBytes();
        for ( int i =0;i <address.length();i++)
        {
            qName[i]=(byte) address.charAt(i);
      //       System.out.print(".  "+qName[i] +" - "+address.charAt(i));
        }
        setPointsVector();
        for(int i=0;i<numberOfPoints;i++)
        {
            qName[pointPositionVector[i]]=(byte)pointVector[i];
        }

    }
    public void setIp()
    {
        qName[0]=4;

    }
    public void setQType ()
    {
        qType[0]=0;
        qType[1]=1;
    }
    public void setQClass()
    {
        qClass[0]=0;
        qClass[1]=1;
    }
    public void setPointsVector()
    {
        pointPositionVector[0]=0;
        int count=1;

        boolean doneFlag=false;
        //get the position of the points
       while (! doneFlag )
       {

           pointPositionVector[count]= address.indexOf(".",pointPositionVector[count-1]+1);
           if(pointPositionVector[count]==-1)
           {
                doneFlag = true;
           }
            else{
           count++;
           }
           numberOfPoints = count;
       }
        //get the size vector
        for (int i=0; i<count;i++)
        {
            int j = i+1;
            if(j== count)
            {
                j=i;
            }
            pointVector[i]=pointPositionVector[j]-pointPositionVector[i]-1;
        }


    }
    public byte [] getDnsQuestion()
    {   setQName();
        setQType();
        setQClass();
        length= address.length();
        byte[] ret_val = new byte[length+5];
        for (int i =0 ; i < length-1; i++){
            ret_val[i]= qName[i];
         //   System.out.print(" * "+qName[i]);
        }

        ret_val[length+0]=qType[0];
        ret_val[length+1]=qType[1];
        ret_val[length+2]=qClass[0];
        ret_val[length+3]=qClass[1];
        length+=5;
        return ret_val;
    }
}
